#include "asgkaDelAgreementThread.h"
#include "asgkaDelete.h"
#include "global.h"
#include "singleMember.h"
#include "asgka_common.h"
#include "common.h"

#include <iostream>
using namespace std;


asgkaDelAgreementThread::asgkaDelAgreementThread()
:m_group(NULL)
{}

asgkaDelAgreementThread::asgkaDelAgreementThread(singleGroup *group,
												 const std::string &name)
:m_group(group),
 m_del_name(name)
{
}

void asgkaDelAgreementThread::init(singleGroup *group, const std::string &name)
{
	m_group = group;
	m_del_name = name;
}

UINT WINAPI asgkaDelAgreementThread::threadWork()
{
	if (m_group == NULL)
		return -1;

	std::string strlogbegin("Key agreement for group (DEL) ");
	strlogbegin.append(m_group->getGroupName());
	strlogbegin.append(" begin!\r\n");
	newLog(strlogbegin);

	asgkaDelete *pChange = new asgkaDelete();
	pChange->correlateAGroup(m_group);

	if (localname.compare(m_group->getGroupLeader()->getMemberName()))
	{
		singleMember *pMember = m_group->getMemberByName(m_del_name);
		asgka_element elementDeckey = pMember->getMemberXigama(m_group->getGroupName());
		pChange->setElementDecryptKey(elementDeckey);

		m_group->deleteAMember(m_del_name);
		pChange->computeMyDecryptKey();
	
		while (!m_group->isCipherTextOK())
		{
			Sleep(10);
		}

		pChange->computeAgreedKey();
		std::string strkeycom("Agreed key of the group named ");
		strkeycom.append(m_group->getGroupName());
		strkeycom.append(" (DEL) OK \r\n");
		newLog(strkeycom);
	}
	else
	{
		singleMember *pMember = m_group->getMemberByName(m_del_name);
		asgka_element elementGrpkeyR = pMember->getMemberpubR(m_group->getGroupName());
		asgka_element elementGrpkeyA = pMember->getMemberpubA(m_group->getGroupName());
		pChange->setElementGroupKeys(elementGrpkeyR, elementGrpkeyA);

		m_group->deleteAMember(m_del_name);
		pChange->generateAgreementKey();
		pChange->publicCiphertexts();
	}

	pChange->updateElementsofGroup();
	c_asgka_element agreedkey = pChange->getAgreedKey();
	for (int i = 0; i < LENGTH; i++)
		cout << agreedkey[i];
	cout << endl;

	delete pChange;
	return 0;
}
